<template>
  <div v-if="isVisible" class="fixed inset-0 z-50 overflow-y-auto mt-20" aria-labelledby="modal-title" role="dialog"
       aria-modal="true">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
      <!-- 背景遮罩 -->
      <div class="fixed inset-0 bg-opacity-75 transition-opacity" aria-hidden="true" @click="closeModal"></div>

      <!-- 弹窗内容 -->
      <div
          class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
          <div class="sm:flex sm:items-start">
            <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
              <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                邀请成员
              </h3>
              <div class="mt-6">
                <div class="flex space-x-3">
                  <!-- 用户名输入框 -->
                  <div class="flex-1">
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input
                        type="text"
                        id="username"
                        v-model="inviteForm.username"
                        class="focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 shadow-sm block w-full sm:text-sm border-gray-300 rounded-md h-12 pl-4"
                        placeholder="请输入用户名"
                    >
                  </div>

                  <!-- 角色选择 -->
                  <div class="w-1/3">
                    <label for="role" class="block text-sm font-medium text-gray-700 mb-1">角色</label>
                    <CustomSelect
                        v-model="inviteForm.role"
                        :options="roleOptions"
                        placeholder="选择角色"
                    />
                  </div>
                </div>

                <div class="mt-5">
                  <button
                      type="button"
                      class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-indigo-600 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:text-sm h-10"
                      @click="inviteUser"
                  >
                    邀请
                  </button>
                </div>
              </div>

              <div class="mt-6">
                <h4 class="text-sm font-medium text-gray-700 mb-4">空间成员 ({{ spaceUsers.length }})</h4>
                <div class="space-y-3 max-h-64 overflow-y-auto pr-2">
                  <div v-for="user in spaceUsers" :key="user.userId"
                       class="flex items-center justify-between py-2 px-3 bg-gray-50 rounded-lg">
                    <div class="flex items-center">
                      <img :src="user.avatar" alt="用户头像" class="h-8 w-8 rounded-full">
                      <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">{{ user.nickname }}</p>
                        <p class="text-xs text-gray-500">
                          <span
                              :class="[
                              'inline-flex items-center px-2 py-0.5 rounded text-xs font-medium', 
                              isSpaceCreator(user.spaceUserRole) ? 'bg-purple-100 text-purple-800' :
                              isSpaceEditor(user.spaceUserRole) ? 'bg-blue-100 text-blue-800' :
                              'bg-green-100 text-green-800'
                            ]"
                          >
                            {{ getSpaceUserRoleName(user.spaceUserRole) }}
                          </span>
                        </p>
                      </div>
                    </div>
                    <div v-if="!isSpaceCreator(user.spaceUserRole)">
                      <button
                          class="text-gray-400 hover:text-red-500 focus:outline-none"
                          @click="removeUser(user.userId)"
                      >
                        <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
          <button
              type="button"
              class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
              @click="closeModal"
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, watch} from 'vue';
import {message} from '@/plugins/message';
import CustomSelect from '@/components/CustomSelect.vue';
import {
  getSpaceUserListByGet,
  SpaceInviteUserRequest,
  spaceInviteUserRequestByPost,
  SpaceUserVo
} from "@/api/space-service";
import {getSpaceUserRoleName, isSpaceCreator, isSpaceEditor, spaceUserRoles} from "@/auth";

const props = defineProps({
  isVisible: {
    type: Boolean,
    required: true,
  },
  spaceId: {
    type: Number,
    required: true
  }
});
const emit = defineEmits(['close']);

// 角色选项
const roleOptions = [
  {role: "viewer", label: '预览者', value: 0},
  {role: "editor", label: '编辑者', value: 1},
];

// 邀请表单
const inviteForm = reactive({
  username: '',
  role: 'viewer'
});

const spaceUsers = ref<SpaceUserVo[]>([]);

watch(() => props.isVisible, (val) => {
  if (val) getSpaceUsers();
});

const getSpaceUsers = async () => {
  if (!props.spaceId) return;
  const res = await getSpaceUserListByGet(props.spaceId)
  if (res.code != 200) {
    message.error("请求失败", res.description)
    return;
  }
  spaceUsers.value = res.data
}

// 邀请用户
const inviteUser = async () => {
  if (!props.spaceId) return;

  if (!inviteForm.username.trim()) {
    message.warning('邀请失败', '用户名不能为空');
    return;
  }

  const spaceInviteUserRequest = {
    id: props.spaceId,
    username: inviteForm.username,
    spaceUserRole: inviteForm.role
  } as SpaceInviteUserRequest

  const res = await spaceInviteUserRequestByPost(spaceInviteUserRequest)
  if (res.code != 200) {
    message.warning('邀请失败', res.description);
    return;
  }else {
    message.success('邀请成功', '');
    inviteForm.username = '';
    getSpaceUsers();
  }
};

// 移除用户
const removeUser = (userId: number) => {
  // TODO: 调用后端移除接口
  const index = spaceUsers.value.findIndex(user => user.userId === userId);
  if (index !== -1) {
    spaceUsers.value.splice(index, 1);
    message.success('已移除该成员', '');
  }
};

// 关闭弹窗
const closeModal = () => {
  emit('close');
};
</script>

<style scoped>
/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  background: #aaa;
}
</style> 